package com.kun.dao.impl;


import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;

import com.kun.dao.CarDao;
import com.kun.entity.CarEntity;
@Repository("CarDaoImpl")
public class CarDaoImpl implements CarDao {

	public String addCar(CarEntity carEntity) {
		ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
		SessionFactory sf = (SessionFactory) app.getBean("sessionFactory");
		Session session = sf.openSession();
		Transaction transaction = session.beginTransaction();
		session.save(carEntity);
		transaction.commit();
		session.close();
		return "success";
	}

	
	public List<CarEntity> getCarInfo(String hql, int id) {
		ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
		SessionFactory sf = (SessionFactory) app.getBean("sessionFactory");
		Session session = sf.openSession();
		Query query = session.createQuery(hql);
		query.setInteger(0,id);
		List<CarEntity> list = query.list();
		return list;
	}


	public List<String> selCarIdById(String hql, int id) {
		ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
		SessionFactory sf = (SessionFactory) app.getBean("sessionFactory");
		Session session = sf.openSession();
		Query query = session.createQuery(hql);
		query.setInteger(0,id);
		List<CarEntity> list = query.list();
		List<String> carList = new ArrayList<String>();
		for(int i=0;i<list.size();i++){
			carList.add(list.get(i).getCarid());
		}
		return carList;
	}


	public List<CarEntity> getCarInfoByCarId(String hql, String id) {
		ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
		SessionFactory sf = (SessionFactory) app.getBean("sessionFactory");
		Session session = sf.openSession();
		Query query = session.createQuery(hql);
		query.setString(0,id);
		List<CarEntity> list = query.list();
		return list;
	}

}
